package com.heatup.apt.api.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.heatup.apt.api.controller.BaseController;
import com.heatup.apt.api.service.CourseService;
import com.heatup.apt.api.service.CourseSignService;
import com.heatup.apt.api.service.DataDictService;
import com.heatup.apt.api.service.UserProductServiceService;
import com.heatup.apt.common.constants.CommonConstants;
import com.heatup.apt.common.constants.CourseConstants;
import com.heatup.apt.common.constants.OrderContants;
import com.heatup.apt.common.constants.UserProductServiceConstants;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.common.util.DateUtil;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.model.DataDict;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.ResourceExample;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.api.ResourceModel;
import com.heatup.apt.model.api.course.*;
import com.heatup.apt.model.coach.CoachInfo;
import com.heatup.apt.model.coach.CoachModel;
import com.heatup.apt.model.course.*;
import com.heatup.apt.model.order.OrderDetail;
import com.heatup.apt.model.order.OrderInfo;
import com.heatup.apt.model.product.ServicePrice;
import com.heatup.apt.model.store.StoreInfo;
import com.heatup.apt.model.user.UserInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 课程详情
 * Created by b3st9u on 16/8/20.
 */
@Service
public class CourseServiceImpl extends BaseController implements CourseService {
    protected static final Logger logger = LoggerFactory.getLogger(CourseServiceImpl.class);
    @Autowired
    private CourseInfoMapper courseInfoMapper;

    @Autowired
    private CoachInfoMapper coachInfoMapper;

    @Autowired
    private CourseScheduleMapper courseScheduleMapper;

    @Autowired
    private StoreInfoMapper storeInfoMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ServicePriceMapper servicePriceMapper;

    @Autowired
    private CourseSignMapper courseSignMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    
    @Autowired
    private UserProductServiceService userProductServiceService;
    
    @Autowired
    private DataDictMapper dataDictMapper;

    @Autowired
    private CourseSignService courseSignService;

    @Autowired
    private CourseCoachMapper courseCoachMapper;

    @Autowired
    private DataDictService dataDictService;

    @Override
    public CourseResultModel queryCourseById(int id) {

        CourseResultModel courseResultModel = null;
        logger.info("读取课程---->");
        CourseInfo courseInfo = courseInfoMapper.queryCourseInfoListById(id);
        logger.info("读取课程----<完成");
        if (courseInfo != null) {
            courseResultModel = new CourseResultModel();
            //只封装需要的数据
            if (courseInfo.getCourseType().equals("3")) {
                //檬营才返回当前系统
                courseResultModel.setDateNow(new Date());
            }
            courseResultModel.setId(courseInfo.getId());
            courseResultModel.setTitle(courseInfo.getTitle());
            courseResultModel.setCourseAttr(Arrays.asList(courseInfo.getCourseAttr().split("#")));
            courseResultModel.setCourseType(courseInfo.getCourseType());
            courseResultModel.setCurrentCount(courseInfo.getCurrentCount());
            courseResultModel.setMinCount(courseInfo.getMinCount());
            courseResultModel.setMaxCount(courseInfo.getMaxCount());
            courseResultModel.setCrowd(courseInfo.getCrowd());
            courseResultModel.setDeadline(courseInfo.getDeadline());
            courseResultModel.setStatus(courseInfo.getStatus());
            if (null != courseInfo.getAnnouncements()) {
                courseResultModel.setAnnouncements(Arrays.asList(courseInfo.getAnnouncements().split("\r\n")));
            }
            courseResultModel.setIntroduce(courseInfo.getIntroduce());
            //查询主教练信息
            logger.info("查询教练---->");
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1, id);
            logger.info("查询教练----<完成");
            if (coachInfo != null) {
                CourseCoachModel courseCoachModel = new CourseCoachModel();
                courseCoachModel.setId(coachInfo.getId());
                courseResultModel.setGoodCourse(Arrays.asList(coachInfo.getGoodCourse().split("#")));
                courseCoachModel.setBriefing(coachInfo.getBriefing());
                courseCoachModel.setHeadImg(coachInfo.getHeadImg());
                courseCoachModel.setNickName(coachInfo.getNickName());
                //查询私教案例
                Resource privateSampleTitleResource = resourceMapper.queryCoachPrivateSampleByCoachId(coachInfo.getId());
                if (privateSampleTitleResource != null) {
                    courseCoachModel.setResourceSampleTitle(privateSampleTitleResource.getText());
                    courseCoachModel.setResourceSampleUrl(privateSampleTitleResource.getUrl());
                }
                courseResultModel.setCoachModel(courseCoachModel);
            }
            //价格
            logger.info("读取课程价格---->");
            courseResultModel.setCoursePrices(selectPriceByCourseId(courseInfo));
            logger.info("读取课程价格----<完成");

            //课程时间安排
            logger.info("读取课程时间安排---->");
            courseResultModel.setSchedule(selectScheduleByCorseId(courseInfo));
            logger.info("读取课程时间安排----<完成");

            //店面信息
            logger.info("读取门店详情---->");
            courseResultModel.setStores(selectStoreByCourseId(courseInfo.getId()));
            logger.info("读取门店详情----<完成");
//            int storeId = courseInfo.getStoreId();
//            StoreInfo storeInfo = storeInfoMapper.selectByPrimaryKey(storeId);
            //课程资源
            logger.info("读取课程详情资源---->");
            courseResultModel.setImages(selectResourceByCourseId(id));
            logger.info("读取课程详情资源----<完成");
            logger.info("返回课程数据======>> " + courseResultModel.toString());
            return courseResultModel;
        }

        return null;
    }

//    public List<CoursePriceModel> selectPriceByCourseId(int id) {
//        CoursePriceExample coursePriceExample = new CoursePriceExample();
//        coursePriceExample.or().andCourseIdEqualTo(id);
//        List<CoursePrice> prices = coursePriceMapper.selectByExample(coursePriceExample);
//        if (prices != null && prices.size() > 0) {
//            List<CoursePriceModel> coursePriceModels = Lists.newArrayList();
//            for (CoursePrice coursePrice : prices) {
//                CoursePriceModel coursePriceModel = new CoursePriceModel();
//                coursePriceModel.setLevel(coursePrice.getLevel());
//                coursePriceModel.setType(coursePrice.getType());
//                coursePriceModel.setPrice(coursePrice.getPrice());
//                coursePriceModels.add(coursePriceModel);
//            }
//            return coursePriceModels;
//        }
//        return null;
//    }

    /**
     * 根据课程Id和类型查询价格。折扣从city_discount表查
     *
     * @param
     * @return
     */
    public CoursePriceModel selectPriceByCourseId(CourseInfo courseInfo) {
        //UserInfo user= getUserInfo();

        CoursePriceModel model = servicePriceMapper.queryCoursePriceModelByCourseId(courseInfo.getId());
        //model.setLevel(user.getLevel());
        model.setPrice(model.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
        return model;
    }

    /**
     * 根据课程查询上课安排
     *
     * @param courseInfo
     * @return
     */
    public String selectScheduleByCorseId(CourseInfo courseInfo) {
//        CourseScheduleExample courseScheduleExample = new CourseScheduleExample();
//        courseScheduleExample.or().andCourseIdEqualTo(courseInfo.getId());
//        List<CourseSchedule> schedules = courseScheduleMapper.selectByExample(courseScheduleExample);
        CourseSchedule courseScheduleDB = new CourseSchedule();
        courseScheduleDB.setCourseId(courseInfo.getId());
        EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
        List<CourseSchedule> schedules = courseScheduleMapper.selectList(entityWrapper);
        String courseTime = "与教练沟通确认";
        if (schedules != null && schedules.size() > 0) {
            CourseSchedule courseSchedule = schedules.get(0);
            if (courseInfo.getCourseType().equals(CourseConstants.CourseType.fun_camp.getType())) { //檬营的时间：显示管理后台配置的文本时间区间字段。修改对比方法为 String.equals String不应该用 == 作对比 blank
                courseTime = courseInfo.getStartEndTime();
            } else {
                if (!courseInfo.getCourseType().equals(CourseConstants.CourseType.private_course.getType())) {//团课和自助健身显示真实的时间  修改对比方法为 String.equals String不应该用 == 作对比 blank
                    if (null != courseSchedule.getStartTime() && null != courseSchedule.getEndTime() && courseInfo.getCourseType().equals(CourseConstants.CourseType.fun_camp.getType())) {
                        //此为檬营日期格式
                        courseTime = courseInfo.getStartEndTime();
                    } else {
                        courseTime = DateUtil.formatDate(courseSchedule.getStartTime(), DateUtil.FMT_DATE_YYYYMMDDHHMM) + "~" + DateUtil.formatDate(courseSchedule.getEndTime(), DateUtil.FMT_DATE_YYYYMMDDHHMM);
                    }

                }
            }

        }
        return courseTime;
    }

    /**
     * 根据课程Id查询店面信息
     *
     * @param id
     * @return
     */
    public List<CourseStoreModel> selectStoreByCourseId(int id) {
        List<StoreInfo> storeInfos = storeInfoMapper.selectByCourseId(id);
        if (storeInfos != null && storeInfos.size() > 0) {
            List<CourseStoreModel> stores = Lists.newArrayList();
            for (StoreInfo storeInfo : storeInfos) {
                CourseStoreModel storeModel = new CourseStoreModel();
                storeModel.setAddress(storeInfo.getAddress());
                storeModel.setAddressLink(storeInfo.getAddressLink());
                storeModel.setLatitude(storeInfo.getLatitude());
                storeModel.setLongitude(storeInfo.getLongitude());
                storeModel.setStoreName(storeInfo.getStoreName());
                storeModel.setStoreId(storeInfo.getId());
                stores.add(storeModel);
            }
            return stores;
        }
        return null;

    }

    /**
     * 根据课程id查询课程对应资源
     *
     * @param id
     * @return
     */
    public Map<String, List<ResourceModel>> selectResourceByCourseId(int id) {
        ResourceExample resourceExample = new ResourceExample();
        resourceExample.or().andParentIdEqualTo(id).andParentTypeEqualTo("2").andResourceParentIdEqualTo(0);
        resourceExample.setOrderByClause("sort_num");
//            int offset = 0;
//            int limit = 4;
//            RowBounds rowBounds = new RowBounds(offset, limit);
//            List<Resource> resources = resourceMapper.selectByExampleWithRowbounds(resourceExample, rowBounds);
        List<Resource> resources = resourceMapper.selectByExample(resourceExample);
        if (resources != null && resources.size() > 0) {
            Map<String, List<ResourceModel>> resourceMap = new HashMap<String, List<ResourceModel>>();
            List<ResourceModel> resourceModels = null;

            for (Resource resource : resources) {

                //这里会有video和category两个类型， 但数据库里的都是camp_video, camp_category, 所以要做下截取
                String key = resource.getResKey();
                if (key.endsWith("_video")) {
                    key = "video";
                } else if (key.endsWith("_category")) {
                    key = "category";
                } else {
                    continue;  //其它类型的资源不用返回
                }
                if (resourceMap.containsKey(key)) {
                    if ("video".equals(key)) {  //视频只需要第一张。（有且只有一张）修改String.equals 为String 对比内容 而不是== 对比引入地址 blank
                        continue;
                    }
                    resourceModels = resourceMap.get(key);
                } else {
                    resourceModels = Lists.newArrayList();
                }
                ResourceModel courseImageModel = new ResourceModel();
                courseImageModel.setId(resource.getId());
                courseImageModel.setLink(resource.getLink());
                courseImageModel.setUrl(resource.getUrl());
                courseImageModel.setTitle(resource.getTitle());
                resourceModels.add(courseImageModel);
                resourceMap.put(key, resourceModels);
            }
            return resourceMap;
        }
        return null;
    }

    @Override
    public CoachModel queryCoachByCourseId(int course_id) {

        return null;
    }


    @Override
    public CourseSignModel querySignInfo(OrderInfo orderInfo, int userId) {
        CourseSignModel model = new CourseSignModel();
        int orderId = orderInfo.getId();
        int serviceId = orderInfo.getServiceId();
        ServicePrice servicePrice = servicePriceMapper.selectByPrimaryKey(serviceId);
        int courseId = servicePrice.getCourseId();

        CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
//
//        CourseSignExample example = new CourseSignExample();
//        example.or().andOrderIdEqualTo(orderId).andUserIdEqualTo(userId);
//        int signedCount = courseSignMapper.countByExample(example);

        CourseSign courseSignDB = new CourseSign();
        courseSignDB.setOrderId(orderId);
        courseSignDB.setUserId(userId);
        int signedCount = courseSignMapper.selectCount(courseSignDB);

        model.setCourseTitle(courseInfo.getTitle());
        model.setOrderId(orderInfo.getId());
        model.setCourseId(courseId);
        Integer totalPeriods = orderDetailMapper.queryOrderDetailByOrderId(orderInfo.getId()).getCourseCount();
        if (totalPeriods == null || totalPeriods == 0) {
            //查询旧版私教订单总数
            totalPeriods = courseInfo.getPeriods();
        }
        model.setTotalPeriods(totalPeriods);
        model.setFinishedPeriods(signedCount);
        model.setLeftPeriods(model.getTotalPeriods() - model.getFinishedPeriods());


        //查已销课数据
//        example = new CourseSignExample();
//        example.or().andOrderIdEqualTo(orderId).andIscloseEqualTo(CommonConstants.YES);
//        example.setOrderByClause("course_number desc");
//        List<CourseSignDetailModel> courseRegList = courseSignMapper.selectDetailByExample(example);

        List<CourseSignDetailModel> courseRegList = courseSignMapper.selectSignDetailWithStoreNameByOrderId(orderId);

        List<CourseRegDetailModel> modelList = new ArrayList<>();
        for (CourseSignDetailModel reg : courseRegList) {
            CourseRegDetailModel regModel = new CourseRegDetailModel();
            regModel.setStoreName(reg.getStoreName());
            regModel.setCourseNumber(reg.getCourseNumber());

            String courseTime = DateUtils.formatTimeRange(reg.getStartTime(), reg.getCloseTime());
            regModel.setTime(courseTime);
            modelList.add(regModel);
        }
        model.setFinishedPeriodList(modelList);
        model.setNeedClosePeriods(signedCount - modelList.size());

        return model;
    }

    @Override
    public int sign(OrderInfo orderInfo, int userId) {
        CourseSignModel model = querySignInfo(orderInfo, userId);
        if (model.getFinishedPeriods() >= model.getTotalPeriods()) {
            return -1;
        }

        int courseNumber = model.getFinishedPeriods() + 1;
        CourseSign sign = new CourseSign();
        sign.setOrderId(model.getOrderId());
        sign.setCourseId(model.getCourseId());
        sign.setUserId(userId);
        sign.setCourseNumber(courseNumber);
        sign.setCreatedBy(userId);
        sign.setCreatedTime(new Date());
        sign.setIsclose(CommonConstants.NO);
        courseSignMapper.insert(sign);

        return courseNumber;
    }

    /**
     * 教练端 团课列表
     *
     * @param paramsMap
     * @return
     */
    @Override
    public ApiResultModel queryCoachTeamCourseListByMobile(Map<String, Object> paramsMap) throws Exception {

        paramsMap.put("pageIndex", (Integer) paramsMap.get("pageIndex") * (Integer) paramsMap.get("pageSize"));

        List<CourseCoachTeamCampPrivateModel> list = courseInfoMapper.queryCoachTeamCourseListByMobile(paramsMap);
        ApiResultModel<Map<String, Object>> resultModel = new ApiResultModel<>();
        Map<String, Object> resultMap = new HashMap<>();
        for (CourseCoachTeamCampPrivateModel course : list) {
            course.setStartTimeStr(DateUtils.format(course.getStartTime(), DateUtils.datePattern));
            course.setStartMinStr(DateUtils.format(course.getStartTime(), DateUtils.shortTimePattern));
        }
        //即将开始的 将列表按天循环拆分
        //按固定日期来拆分
        if (paramsMap.get("type").equals("0")) {
            Map<String, Object> tempMap = new HashMap<>();
            List<Map<String, Object>> resultDateMap = new ArrayList<>();
            List<CourseCoachTeamCampPrivateModel> tempList;

            Calendar startCalendar = Calendar.getInstance();
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.add(Calendar.DATE, 7);

            while (startCalendar.before(endCalendar)) {
                tempMap = new HashMap<>();
                tempList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getStartTime() != null && DateUtils.getDateShort(list.get(i).getStartTime()).compareTo(DateUtils.getDateShort(startCalendar.getTime())) == 0) {
                        tempList.add(list.get(i));
                        tempMap.put("weekday", list.get(i).getWeekday());
                        tempMap.put("leftDays", list.get(i).getLeftDays());
                    }
                }

                if (tempList.size() > 0) {
                    tempMap.put("courseList", tempList);
                    resultDateMap.add(tempMap);
                }
                startCalendar.add(Calendar.DATE, 1);//每次循环增加一天
            }

            resultMap.put("list", resultDateMap);
        } else {
            //已结束的团课不拆分
            resultMap.put("list", list);
        }

        resultMap.put("count", courseInfoMapper.queryCoachTeamCourseCountByMobile(paramsMap));
        resultModel.setData(resultMap);
        return resultModel;
    }

    /**
     * 教练端 檬营列表
     *
     * @param paramsMap
     * @return
     */
    @Override
    public ApiResultModel queryCoachCampCourseListByMobile(Map<String, Object> paramsMap) {

        ApiResultModel<Map<String, Object>> resultModel = new ApiResultModel<>();
        Map<String, Object> resultMap = new HashMap<>();
        paramsMap.put("pageIndex", (Integer) paramsMap.get("pageIndex") * (Integer) paramsMap.get("pageSize"));
        //当前只按 报名截止时间来查
        List<CourseCoachTeamCampPrivateModel> list = new ArrayList<>();
        if (paramsMap.get("type").equals("0")) {
            //查询我的授课
            list = courseInfoMapper.queryCoachCampCourseListByMobile(paramsMap);
            resultMap.put("count", courseInfoMapper.queryCoachCampCourseCountByMobile(paramsMap));
        }
        if (paramsMap.get("type").equals("1")) {
            //查询历史记录
            list = courseInfoMapper.queryCoachCampCourseHistoryListByMobile(paramsMap);
            resultMap.put("count", courseInfoMapper.queryCoachCampCourseHistoryCountByMobile(paramsMap));
        }
        if (paramsMap.get("type").equals("0")) {
            //已到报名截止时间且成营 在前
            //未到报名截止时间 显示报名中
            //成营未成营 拆分
            List<CourseCoachTeamCampPrivateModel> yesList;
            List<CourseCoachTeamCampPrivateModel> notList;
            List<List<CourseCoachTeamCampPrivateModel>> resultList = new ArrayList<>();

            yesList = new ArrayList<>();
            //已到报名截止时间 + 成营
            Date now = new Date();
            for (CourseCoachTeamCampPrivateModel courseModel : list) {
                if (courseModel.getCampStatus()) {
                    yesList.add(courseModel);
                }
            }
//        if (notList.size() > 0) {
            //已成营 没数据也需要返回空给前端
            resultList.add(yesList);
//        }
            notList = new ArrayList<>();
            //未到报名时间
            for (CourseCoachTeamCampPrivateModel courseModel : list) {
                if (now.before(courseModel.getDeadline())) {
                    notList.add(courseModel);
                }
            }
            if (notList.size() > 0) {
                resultList.add(notList);
            }
            resultMap.put("list", resultList);
        } else {
            //已到报名截止时间未成营 不显示 在已完成列表
            //按最后一次签到关闭的时间
            resultMap.put("list", list);
        }
        resultModel.setData(resultMap);
        return resultModel;
    }


    /**
     * 教练端 私教列表
     *
     * @param paramsMap 请求参数
     *        type        记录类型 默认 0我的授课 1授课记录
     *        privateType 课程类型 1:私教课 2:体测 3:体验 4:咨询
     * @return 私教列表
     */
    @Override
    public Map<String, Object> queryCoachPrivateCourseListByMobile(Map<String, Object> paramsMap) {

        paramsMap.put("pageIndexs",(Integer) paramsMap.get("pageIndex"));
        paramsMap.put("pageIndex", (Integer) paramsMap.get("pageIndex") * (Integer) paramsMap.get("pageSize"));
        if (paramsMap == null || paramsMap.size() == 0) {
            throw new RuntimeException("教练端 私教列表接口查询参数不可为 null");
        }
        Integer privateType = (Integer) paramsMap.get("privateType");
        Map<String, Object> resultMap = new HashMap<>();

        switch (privateType) {
            case 1:
                resultMap = getPrivateNormalList(paramsMap);
                break;
            case 2:
                resultMap = getPrivateBodyExaminationList(paramsMap);
                break;
            case 3:
                resultMap = getPrivateExperienceList(paramsMap);
                break;
            case 4:
                resultMap = getPrivateConsultList(paramsMap);
                break;
        }

        //添加4种类型课程的计数
        if (paramsMap.get("type").equals("0")) {
            //授课
            resultMap.put("privateNormalCount", courseInfoMapper.queryCoachPrivateCourseCount(paramsMap));
            resultMap.put("privateBodyExaminationCount", orderInfoMapper.queryCoachPrivateBodyExaminationOrderCount(paramsMap));
            resultMap.put("privateExperienceCount", orderInfoMapper.queryCoachPrivateExperienceOrderCount(paramsMap));
            resultMap.put("privateConsultCount", orderInfoMapper.queryCoachPrivateConsultOrderCount(paramsMap));
        }
        if (paramsMap.get("type").equals("1")) {
            //记录
            resultMap.put("privateNormalCount", courseSignMapper.queryCoachPrivateCourseSignCount(paramsMap));
            resultMap.put("privateBodyExaminationCount", orderInfoMapper.queryCoachPrivateBodyExaminationOrderHistoryCount(paramsMap));
            resultMap.put("privateExperienceCount", orderInfoMapper.queryCoachPrivateExperienceOrderHistoryCount(paramsMap));
            resultMap.put("privateConsultCount", orderInfoMapper.queryCoachPrivateConsultOrderCount(paramsMap));
        }

        return resultMap;
    }

    /**
     * 查询私教 体测订单 privateType = 2
     *
     * @author blank 2017/8/5 上午11:05
     */
    private Map<String, Object> getPrivateBodyExaminationList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap<>();
        if (paramsMap.get("type").equals("0")) {
            //授课
            resultMap.put("list", orderInfoMapper.queryCoachPrivateBodyExaminationOrderList(paramsMap));
            resultMap.put("count", orderInfoMapper.queryCoachPrivateBodyExaminationOrderCount(paramsMap));
        }
        if (paramsMap.get("type").equals("1")) {
            //记录
            resultMap.put("list", orderInfoMapper.queryCoachPrivateBodyExaminationOrderHistoryList(paramsMap));
            resultMap.put("count", orderInfoMapper.queryCoachPrivateBodyExaminationOrderHistoryCount(paramsMap));
        }
        return resultMap;

    }


    /**
     * 查询私教 体验订单 privateType = 3
     *
     * @author blank 2017/8/5 上午11:05
     */
    private Map<String, Object> getPrivateExperienceList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap<>();
        if (paramsMap.get("type").equals("0")) {
            //授课
            resultMap.put("list", orderInfoMapper.queryCoachPrivateExperienceOrderList(paramsMap));
            resultMap.put("count", orderInfoMapper.queryCoachPrivateExperienceOrderCount(paramsMap));
        }
        if (paramsMap.get("type").equals("1")) {
            //记录
            resultMap.put("list", orderInfoMapper.queryCoachPrivateExperienceOrderHistoryList(paramsMap));
            resultMap.put("count", orderInfoMapper.queryCoachPrivateExperienceOrderHistoryCount(paramsMap));
        }
        return resultMap;

    }




    /**
     * 查询私教 咨询订单 privateType = 4
     *
     * @author blank 2017/8/4 下午4:52
     */
    private Map<String, Object> getPrivateConsultList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", orderInfoMapper.queryCoachPrivateConsultOrderList(paramsMap));
        resultMap.put("count", orderInfoMapper.queryCoachPrivateConsultOrderCount(paramsMap));

        return resultMap;
    }

    /**
     * 查询私教 普通私教课程订单 privateType = 1
     *
     * @author blank 2017/8/4 下午4:48
     */

    private Map<String, Object> getPrivateNormalList(Map<String, Object> paramsMap) {

        List<CourseCoachTeamCampPrivateModel> list;
        Map<String, Object> resultMap = new HashMap<>();
        if (paramsMap.get("type").equals("0")) {
            //授课
            list = courseInfoMapper.queryCoachPrivateCourseList(paramsMap);
            for (CourseCoachTeamCampPrivateModel course : list) {
                //去除空user
                for (int i = 0; i < course.getUsers().size(); i++) {
                    if (course.getUsers().get(i).getId() == null) {
                        course.getUsers().remove(i);
                    }
                }
            }
            resultMap.put("count", courseInfoMapper.queryCoachPrivateCourseCount(paramsMap));
            resultMap.put("list", list);
        }
        if (paramsMap.get("type").equals("1")) {
            //记录
            resultMap = courseSignService.queryCoachPrivateCourseSignList(paramsMap);
//            resultMap.put("list", courseInfoMapper.queryCoachPrivateCourseHistoryList(paramsMap));
//            resultMap.put("count", courseInfoMapper.queryCoachPrivateCourseHistoryCount(paramsMap));
        }

        return resultMap;
    }

    public CourseInfo getCourseInfoById(Integer courseId) {
        return courseInfoMapper.selectById(courseId);
    }

    public Map<String, Object> getPrice(Integer orderId) {
        return courseInfoMapper.getOrderInfo(orderId);
    }

    /**
     * API 查询课程详情(团课/私教/檬营)
     *
     * @param courseId 课程 ID
     * @param userId   用户 ID
     * @return 课程详情
     */
    @Override
    public CourseDetailModel queryCourseByCourseId(Integer courseId, Integer userId) {
        if (courseId == null) {
            throw new RuntimeException("课程 ID 不能为空!");
        }
        CourseDetailModel course = courseInfoMapper.queryCourseById(courseId);
        
        // 判断用户是否拥有年卡服务
        Integer hasYearCardService = userProductServiceService.checkUserHasYearCardService(userId);
        course.setHasYearCardService(hasYearCardService);
    	// 查询该用户是否购买过此课程的订单
        Integer hasCourseOrder = orderInfoMapper.checkUserIsHasThisCourseOrderByCourseIdAndUserIdAndOrderType(courseId, userId, Integer.valueOf(course.getCourseType()));
        if (course != null) {
            if (course.getCourseType().trim().equals(CourseConstants.CourseType.fun_camp.getType().trim())) {
                course.setDateNow(new Date());
            }
            course.setCourseAttr(Arrays.asList(course.getCourseAttrTemp().split("#")));
            course.setCourseAttrTemp(null);
            course.setGoodCourse(Arrays.asList(course.getGoodCourseTemp().split("#")));
            course.setGoodCourseTemp(null);
            course.setImages(getImages(course.getResources()));
            course.setResources(null);
            course.setHasCourseOrder(hasCourseOrder > 0);// 判断该用户是否购买过该课程
            
            if (course.getCourseType().equals("2")) {
                //私教购买次数限制课程校验
                if ( userId != null) {
                    course.setBougthOne(orderInfoMapper.queryOrderLimitByCourseIdAndUserId(courseId, userId) == 1);
                }
                // 如果是私教课程的 需要判断是否含有年卡的 如果含有允许用户多次购买 
                if(course.getProductServiceDetailId() != null && course.getProductServiceDetailId() > 0) {
                	course.setHasYearCardService(UserProductServiceConstants.ISVALID);
                }
                course.setHasCourseOrder(false);
            }
        }
        return course;
    }

    private Map<String, List<Resource>> getImages(List<Resource> resourceList) {
        if (resourceList != null && resourceList.size() > 0) {
            Map<String, List<Resource>> resourceMap = new HashMap<String,List<Resource>>();
            for (Resource resource : resourceList) {

                //这里会有video和category两个类型， 但数据库里的都是camp_video, camp_category, 所以要做下截取
                String key = resource.getResKey();
                if (key.endsWith("_video")) {
                    key = "video";
                } else if (key.endsWith("_category")) {
                    key = "category";
                } else {
                    continue;  //其它类型的资源不用返回
                }
                if (resourceMap.containsKey(key)) {
                    if ("video".equals(key)) {  //视频只需要第一张。（有且只有一张）修改String.equals 为String 对比内容 而不是== 对比引入地址 blank
                        continue;
                    }
                    resourceList = resourceMap.get(key);
                } else {
                    resourceList = Lists.newArrayList();
                }
                Resource courseImageModel = new Resource();
                courseImageModel.setId(resource.getId());
                courseImageModel.setLink(resource.getLink());
                courseImageModel.setUrl(resource.getUrl());
                courseImageModel.setTitle(resource.getTitle());
                resourceList.add(courseImageModel);
                resourceMap.put(key, resourceList);
            }
            return resourceMap;
        }
        return null;
    }
    
    @Override
    public List<CoachFeeDetailVo> queryCoachFeeDetail(Map<String, Object> paramsMap) {
        return courseInfoMapper.queryCoachFeeDetail(paramsMap);
    }

    /**
     * @Author: timo
     * @Date: 2018/7/13 11:07
     * @Description: 查询私教咨询详情下单详情
     * @return:
     *
     */
	@Override
	public Map<String, Object> queryConsultCourseDetail() {
		Map<String,Object> resultMap = new HashMap<>();
		// 门店列表 start
		List<StoreInfo> storeList = storeInfoMapper.queryAllStoreList();
		// 时间段
//		List<DataDict> consultTimeList = dataDictMapper.queryDataDictCodeByDictTypeAndStatus("COACH_ADVISORY_TIME", "1");
        resultMap = dataDictService.queryCoachAdvisoryTime(new Date());
        if (resultMap == null || resultMap.size() == 0){
            new HashMap<>();
        }else {
            String startTimes = (String) resultMap.get("startTime");
            String endTimes = (String) resultMap.get("endTime");
            resultMap.put("startTime",startTimes.split("\\s")[1]);
            resultMap.put("endTime",endTimes.split("\\s")[1]);
        }



		ServicePrice servicePrice = servicePriceMapper.queryServicePriceByServiceTypeOne(OrderContants.OrderType.private_bespeak.getIndex());
		resultMap.put("storeList", storeList);
//		resultMap.put("consultTimeList", consultTimeList);
//		resultMap.put("startTime",startTime);
//        resultMap.put("endTime",endTime);
		resultMap.put("courseType", OrderContants.OrderType.private_bespeak.getIndex());
		resultMap.put("orderType", OrderContants.OrderType.private_bespeak.getIndex());
		resultMap.put("serviceId", servicePrice == null ? 0 :servicePrice.getId());
		return resultMap;
	}

    @Override
    public Map queryPrivateCourseSignDetailLog(UserInfo userInfo, Integer orderId) {
        ServicePrice servicePrice = servicePriceMapper.queryServicePriceByOrderId(orderId);
        if (servicePrice == null) return null;
        if(servicePrice.getServiceType() == OrderContants.OrderType.pt.getIndex()){
            return queryPtCourseSignDetailLog(userInfo, orderId, servicePrice);
        }else if(servicePrice.getServiceType() == OrderContants.OrderType.physical_examination.getIndex()
                || servicePrice.getServiceType() == OrderContants.OrderType.secret_experience.getIndex()){

            return queryPlpeOrPlecCourseSignDetailLog(userInfo, orderId, servicePrice);
        }
        return null;
    }

    /**
     *@Author: timo
     *@Date: 2018/4/4 18:39
     *@Description:
     * 查询私教的签到详情
     *
     */
    public Map queryPtCourseSignDetailLog(UserInfo userInfo, Integer orderId, ServicePrice servicePrice){

        List<UserCourseSignDetailModel> userCourseSignDetailModels = courseSignMapper.queryUserPrivateCourseSignDetailLog(userInfo.getId(), orderId);
        List<String> coachName = courseCoachMapper.queryCourseCoachNameByCourseId(servicePrice.getCourseId());

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("list",userCourseSignDetailModels);
        resultMap.put("courseName",servicePrice.getServiceName());
        resultMap.put("coachNameList",coachName);
        return resultMap;
    }

    /**
     *@Author: timo
     *@Date: 2018/4/4 18:39
     *@Description:
     * 查询体测体验课的签到详情
     *
     */
    public Map queryPlpeOrPlecCourseSignDetailLog(UserInfo userInfo, Integer orderId, ServicePrice servicePrice){

        // 签到详情列表
        List<UserCourseSignDetailModel> userCourseSignDetailModels = courseSignMapper.queryUserPlpeOrPlecCourseSignDetailLog(userInfo.getId(), orderId);
        // 因为下单的时候就能确定上课的教练所以这里直接查出教练
        OrderDetail orderDetail = orderDetailMapper.queryOrderDetailByOrderId(orderId);
        // 查询教练
        CoachInfo coachInfo = coachInfoMapper.selectById(orderDetail.getCoachId());
        List<String> coachName = new ArrayList<>();
        coachName.add(coachInfo.getNickName());
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("list",userCourseSignDetailModels);
        resultMap.put("courseName",servicePrice.getServiceName());
        resultMap.put("coachNameList",coachName);
        return resultMap;
    }
}
